package com.fishingwithme.android.ui.screens.map.handlers

import com.fishingwithme.android.R

/**
 * 拾取点处理器 - 用于在地图上选择位置
 */
class PickupPointEventHandler : BaseHandler() {
    override val key: String = "pickupPoint"
    override val icon: Int = R.mipmap.pickup  // 使用"place"图标表示选择位置

    private var fishingSpotMarker: com.tencent.tencentmap.mapsdk.maps.model.Marker? = null

    override fun doAction() {
        super.doAction()

        // 设置点选择回调 when the handler becomes active
        this.setOnPointSelectedCallback { latitude, longitude ->
            try {
                // 清除之前的选择 using context management
                fishingSpotMarker?.let {
                    removeMarkerFromMap(it)
                }

                // 创建新的标记
                val latLng = com.tencent.tencentmap.mapsdk.maps.model.LatLng(latitude, longitude)
                val markerOptions = com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions(latLng)
                    .title("钓点位置")
                    .snippet("点击地图选择的钓点位置")
                    .infoWindowEnable(true)

                fishingSpotMarker = map?.addMarker(markerOptions)
                fishingSpotMarker?.showInfoWindow()

                // Add marker to context for management
                fishingSpotMarker?.let {
                    addMarkerToMap(it)
                }

                // 存储钓点位置到data中
                val pointData = mapOf(
                    "latitude" to latitude,
                    "longitude" to longitude
                )

                // 更新共享的data
                data?.set("fishingSpot", pointData)
            } catch (e: Exception) {
                android.util.Log.w("PickupPointEventHandler", "Error handling point selection", e)
            }
        }
    }

    override fun reset() {
        super.reset()
        try {
            // Remove marker using context management
            fishingSpotMarker?.let {
                removeMarkerFromMap(it)
            }
        } catch (e: Exception) {
            android.util.Log.w("PickupPointEventHandler", "Error removing marker", e)
        }
        fishingSpotMarker = null
    }
}